package com.lincoln.cloud.serverclient.bean;

import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 协议结构接口
 *
 * @author lincoln
 */
public abstract class BaseProtocol extends Vector<Byte> {
    /**
     * 该协议的指令
     *
     * @return
     */
    public abstract byte[] getCmd();

    /**
     * 检查这个包是否合法
     *
     * @return
     */
    public abstract boolean verify();

    /**
     * 因为最终是以byte发出,所以需要有转换成byte
     *
     * @return
     */
    public byte[] toBytes() {
        byte[] res = new byte[size()];
        int i = 0;
        for (Byte b : this) {
            res[i++] = b;
        }
        return res;
    }

    @Override
    public String toString() {
        return "抽象类的toString";
    }


    /**
     * 消息号最大值
     */
    private static final int NO_MAX = 255;

    /**
     * 消息号队列
     */
    public static ConcurrentLinkedQueue<Integer> noQueue = new ConcurrentLinkedQueue<>();

    /**
     * 已使用的消息号,消息号-命令
     */
    public static ConcurrentHashMap<Integer, byte[]> waitNo = new ConcurrentHashMap<>();

    public static int getNo(byte[] cmd) {
        if (noQueue == null || noQueue.size() <= 0) {
            noQueue = new ConcurrentLinkedQueue<>();
            for (int i = 0; i < NO_MAX; i++) {
                noQueue.add(i);
            }
        }
        int res = noQueue.poll();
        if (waitNo == null) {
            waitNo = new ConcurrentHashMap<>(NO_MAX);
        }
        waitNo.put(res, cmd);
        return res;
    }

    public static void addNo(int no) {
        noQueue.add(no);
        waitNo.remove(no);
    }

    public static boolean checkNo(int no, byte[] cmd) {
        if (waitNo == null) {
            waitNo = new ConcurrentHashMap<>(NO_MAX);
        }
        byte[] c = waitNo.get(no);
        if (c == null || c != cmd) {
            return false;
        }
        return true;
    }
}
